import {useUserStore} from '@/store/user.js';
import {useShopStore} from '@/store/shop.js'
import Request from './request'
import {
	getToken
} from '../auth.js'
import mHelper from '@/utils/helper'
import indexConfig from '@/config/index.config'

const http = new Request()

http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseUrl = indexConfig.baseUrl /* 根域名不同 */
	config.header = {
		...config.header
	}
	return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
http.validateStatus = (statusCode) => {
	return statusCode === 200
}

http.interceptor.request((config, cancel) => {
	/* 请求之前拦截器 */
	let network = true
	uni.getNetworkType({
		success: (res) => {
			if (res.networkType == 'none') {
				network = false
				uni.showToast({
					title: '网络异常，请检查网络状态',
					icon: 'none',
					duration: 2000
				})
			}
		}
	});
	if (!network) return false;
	const shopStore = useShopStore();
	config.header = {
		...config.header,
		authorization: getToken() ? 'Bearer ' + getToken() : '',
		shopId:shopStore.id
	}
	return config
})

http.interceptor.response((response) => {
	/* 请求之后拦截器 */
	const res = response.data
	// 请求状态码
	if (response.statusCode !== 200) { // 服务端返回的状态码不等于200，则reject()
		if(response.statusCode === 403){
			uni.navigateTo({
			    url:"pages/httpStatus/403"
			})
		}else{
			uni.showToast({
				title: res.erroMessage || '请求失败',
				icon: 'none'
			})
		}
		return Promise.reject(new Error(res.erroMessage || '请求失败'))
	}

	if (res.hasOwnProperty('Code') && res.hasOwnProperty('ErroMessage')) {
		if (res.Code == 1001) {
			uni.showToast({
				title: res.ErroMessage,
				icon: 'none'
			})
			uni.redirectTo({
				url: '/pages/login/valid'
			})
			return Promise.reject(new Error(res.ErroMessage || '请求失败'))
		}
		if (res.Code == 1000) {
			const userStore = useUserStore();
			userStore.logout()
		}
		uni.showToast({
			title: res.ErroMessage || '请求失败',
			icon: 'none'
		})
		return Promise.reject(new Error(res.ErroMessage || '请求失败'))
	}
	
	if (res.hasOwnProperty('code') && res.hasOwnProperty('erroMessage')) {
		if(res.code === 403){
			uni.navigateTo({
			    url:"pages/httpStatus/403"
			})
		};
		if (res.code == 1001) {
			uni.showToast({
				title: res.erroMessage,
				icon: 'none'
			})
			uni.redirectTo({
				url: '/pages/login/valid'
			})
			return Promise.reject(new Error(res.erroMessage || '请求失败'))
		}
		if (res.code == 1000) {
			const userStore = useUserStore();
			userStore.logout()
		}
		if (res.code == 20409) {
			uni.showToast({
				title: '用户没有实名认证，请先认证',
				icon: 'none'
			})
			mHelper.getTabbar()
			uni.switchTab({
				url: '/pages/wo/index'
			})
			return Promise.reject(new Error('用户没有实名认证，请先认证'))
		}
		return res
	}
	return res
}, (response) => { // 请求错误做点什么
	if (response.statusCode !== 200) { // 服务端返回的状态码不等于200，则reject()
		if(response.statusCode === 403){
			uni.reLaunch({
				url: '/pages/httpStatus/403'
			})
		}else{
			uni.showToast({
				title: response.errMsg || '请求失败',
				icon: 'none'
			})
		}
		return Promise.reject(response)
	}
	
})
export default http
